$(function () {
    //获取id
    var id = tools.queryString().id || 1;
    var token = localStorage.token;
    //页面加载时默认样式
    $($(".productMsgOrComments")[0]).addClass("showMsgOrComments")
    $($(".allCommentList")).addClass("showcommentList");
    //获取商品详情
    $.ajax({
        type: "get",
        // url:domain.online + "/api/product",
        url: domain.test + "/getproductdetail",
        data: { id: id },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("token", token);
        },
        success: function (data) {
            if (data.data.rtnCode === 200) {
                // if(data.rtnCode === 200) {
                var productDetail = data.data.data;
                console.log(productDetail);
                // var productDetail = data.data;
                //商品图片轮播图
                $(".swiper-container").html(template("productAutoImg", { pics: productDetail.pics }));
                var mySwiper = new Swiper('.swiper-container', {
                    autoplay: 3000,
                    pagination: ".swiper-pagination",
                    loop: true,
                    autoplayDisableOnInteraction: false
                });
                //商品信息
                document.title = productDetail.productName;
                $(".product_Name").html(template("productMsgAndPrice", { msg: productDetail }));
                //喜欢商品
                var love = productDetail.love;
                love.loving = productDetail.loving;
                console.log(love);
                $('.like').html(template("peopleLikeProduct", { love: love }));
                //商品详情
                $(".productMsg").html(template("msgContent", { details: productDetail.details }));
                $("img.lazy").lazyload({
                    palceholder: "../../img/loading.gif",
                    effect: "fadeIn",
                    threshold: 50,
                    failurelimit: 10
                });
            }
        }
    });
    //获取商品评论数
    $.ajax({
        type: "get",
        url: domain.test + "/getproductcommentsnum",
        // url:domain.online + "/api/product/review/number",
        data: { id: id },
        success: function (data) {
            if (data.data.rtnCode === 200) {
                // if(data.rtnCode === 200) {
                var commentsNum = data.data.data;
                // var commentsNum = data.data;
                $(".btn").html(template("btns", { commentsNum: commentsNum.hao + commentsNum.zhong + commentsNum.cha }));
                $($(".msgAndcommentsBtn")[0]).addClass("btnActive");
                $(".commentClassify").html(template("commentClassifyBtn", { allCommentNum: commentsNum }));
                $($(".commentItem")[0]).addClass("activeComments");
            }
        }
    });
    //获取所有商品评论
    $.ajax({
        type: "get",
        url: domain.test + "/getproductallcomments",
        // url: domain.online + "/api/product/review/list",
        data: { id: id },
        success: function (data) {
            if (data.data.rtnCode === 200) {
                // if(data.rtnCode === 200) {
                var comments = data.data.data;
                // var comments = data.data;
                $(".allCommentList").html(template("allCommentsTpl", { commenList: comments.list }));
                getGoodComments(id);
            }
        }
    });
    //获取商品好评列表
    function getGoodComments(id) {
        $.ajax({
            type: "get",
            url: domain.test + "/getproductgoodcomments",
            // url: domain.online + "/api/product/review/list",
            data: { id: id, score: 1, pageNum: 1 },
            success: function (data) {
                if (data.data.rtnCode === 200) {
                    // if(data.rtnCode === 200) {
                    var comments = data.data.data;
                    // var comments = data.data;
                    $(".goodCommentList").html(template("goodCommentsTpl", { commenList: comments.list }));
                    getNeutralComments(id);
                }
            }
        });
    }
    //获取商品中评列表
    function getNeutralComments(id) {
        $.ajax({
            type: "get",
            url: domain.test + "/getproductneutralcomments",
            // url: domain.online + "/api/product/review/list",
            data: { id: id, score: 0, pageNum: 1 },
            success: function (data) {
                if (data.data.rtnCode === 200) {
                    // if(data.rtnCode === 200) {
                    var comments = data.data.data;
                    // var comments = data.data;
                    $(".neutralCommentList").html(template("neutralCommentsTpl", { commenList: comments.list }));
                    getBadComments(id);
                }
            }
        });
    }
    //获取商品差评列表
    function getBadComments(id) {
        $.ajax({
            type: "get",
            url: domain.test + "/getproductbadcomments",
            // url: domain.online + "/api/product/review/list",
            data: { id: id, score: -1, pageNum: 1 },
            success: function (data) {
                if (data.data.rtnCode === 200) {
                    // if(data.rtnCode === 200) {
                    var comments = data.data.data;
                    // var comments = data.data;
                    $(".badCommentList").html(template("badCommentsTpl", { commenList: comments.list }));
                }
            }
        });
    }
    //商品详情和评论的切换
    $(".btn").on("click", ".msgAndcommentsBtn", function () {
        $(".msgAndcommentsBtn").removeClass("btnActive");
        $(this).addClass("btnActive");
        var index = $(this).attr("index");
        $(".productMsgOrComments").removeClass("showMsgOrComments");
        $($(".productMsgOrComments")[index - 1]).addClass("showMsgOrComments");
    });
    //商品评论的切换
    $(".commentClassify").on("click", ".commentItem", function () {
        $(".commentItem").removeClass("activeComments");
        $(this).addClass("activeComments");
        var index = $(this).attr("index");
        $(".commentList").removeClass("showcommentList");
        $($(".commentList")[index - 1]).addClass("showcommentList");
    });
    //客服弹出层
    $(".kefu").on("click", function () {
        var width = window.screen.availWidth;
        var height = window.screen.availHeight;
        $(".kefuMarsk").css({
            "width": width,
            "height": height,
            "display": "block"
        });
    });
    //隐藏客服弹出层
    $(".cancle").on("click", function () {
        $(".kefuMarsk").css("display", "none");
    });
    //复制客服微信
    var clipboardOne = new Clipboard(document.querySelector(".copyBtnOne"));
    var clipboardTwo = new Clipboard(document.querySelector(".copyBtnTwo"));
    //加入购物车
    var skuArr = [];
    //获取商品sku
    $.ajax({
        type: "get",
        url: domain.test + "/getproductsku",
        data: { id: id },
        success: function (response) {
            if (response.data.rtnCode === 200) {
                var skuDetail = response.data.data;
                // console.log(skuDetail);
                console.log(skuDetail.pSkuArray);
                console.log(skuDetail.skus);
                $.each(skuDetail.pSkuArray, function (index, value) {
                    var tempObj = {};
                    tempObj.skuId = value.skuId;
                    tempObj.price = value.price;
                    tempObj.diamond = value.diamond;
                    tempObj.cash = value.diamondPrice;
                    tempObj.inventory = value.inventory;
                    tempObj.pic = value.pic;
                    tempObj.skuCode = value.skuCode;
                    skuArr.push(tempObj);
                });
                $(".carAndBuyMarsk").html(template("carAndBuyMarsk", { skuDetail: skuDetail }));
                var sku = "";
                var skuCode = "";
                $.each($(".listItem"), function (index, value) {
                    var index = parseInt($(value).attr("data-index"));
                    if (index === 0) {
                        sku += $(value).parent().parent().find(".skuName").html() + ":" + $(value).html() + " ";
                        skuCode += $(value).attr("data-code") + ";";
                        $(value).attr("data-checkStatus", 1);
                        $(value).css("background-color", "#ffa31a");
                    }
                });
                $.each(skuArr, function (index, value) {
                    if (skuCode === value.skuCode) {
                        $(".carAndBuyMarsk .pic").attr("data-skuId", value.skuId);
                        $(".carAndBuyMarsk .pic img").attr("src", value.pic);
                        $(".skuPrice").attr("data-diamond", value.diamond);
                        $(".skuPrice").attr("data-cash", value.cash.toFixed(2));
                        $(".skuPrice").html(value.price.toFixed(2));
                        $(".inventory").html(value.inventory);
                        $(".showSku").html(sku);
                    }
                });
            }
        }
    });
    $(".addCar").on("click", function () {
        marskAnimate("加入购物车", 0);
    });
    //切换规格
    $(".carAndBuyMarsk").on("click", ".listItem", function () {
        var checkStatus = parseInt($(this).attr("data-checkStatus"));
        if (checkStatus === 1) return false;
        var index = parseInt($(this).attr("data-index"));
        $(this).parent().find(".listItem").css("background-color", "#f2f2f2");
        $(this).css("background-color", "#ffa31a");
        $(this).parent().find(".listItem").attr("data-checkStatus", 0);
        $(this).attr("data-checkStatus", 1);
        var sku = "";
        var skuCode = "";
        $.each($(".listItem"), function (index, value) {
            if (parseInt($(value).attr("data-checkStatus")) === 1) {
                sku += $(value).parent().parent().find(".skuName").html() + ":" + $(value).html() + " ";
                skuCode += $(value).attr("data-code") + ";";
            }
        });
        $(".showSku").html(sku);
        console.log(skuCode);
        $.each(skuArr, function (index, value) {
            if (skuCode === value.skuCode) {
                $(".carAndBuyMarsk .pic").attr("data-skuId", value.skuId);
                $(".carAndBuyMarsk .pic img").attr("src", value.pic);
                $(".skuPrice").attr("data-diamond", value.diamond);
                $(".skuPrice").attr("data-cash", value.cash.toFixed(2));
                $(".skuPrice").html(value.price.toFixed(2));
                $(".inventory").html(value.inventory);
                $(".showSku").html(sku);
                console.log(value.inventory,parseInt($(".pNum .num").html()));
                if (value.inventory > 0 && value.inventory >= parseInt($(".pNum .num").html())) {
                    $(".footerBtn").css("background-color", "#1f1f1f");
                    if (parseInt($(".footerBtn").attr("data-status")) === 0) {
                        $(".footerBtn").attr("canDo", 1);
                        $(".footerBtn").html("加入购物车");
                    } else if (parseInt($(".footerBtn").attr("data-status")) === 1) {
                        $(".footerBtn").attr("canDo", 1);
                        $(".footerBtn").html("立即购买");
                    }
                } else if (value.inventory === 0 || value.inventory < parseInt($(".pNum .num").html())) {
                    $(".footerBtn").css("background-color", "#ebebeb");
                    $(".footerBtn").attr("canDo", 0);
                    $(".footerBtn").html("缺货");
                }
            }
        });
        // if(inventoryArr[index]>0&&inventoryArr[index]>=parseInt($(".pNum .num").html())) {
        //     $(".footerBtn").css("background-color","#1f1f1f");
        //     if(parseInt($(".footerBtn").attr("data-status"))===0) {
        //         $(".footerBtn").attr("canDo",1);
        //         $(".footerBtn").html("加入购物车");
        //     }else if(parseInt($(".footerBtn").attr("data-status"))===1) {
        //         $(".footerBtn").attr("canDo",1);
        //         $(".footerBtn").html("立即购买");
        //     }
        // }else if(inventoryArr[index]===0||inventoryArr[index]<parseInt($(".pNum .num").html())) {
        //     $(".footerBtn").css("background-color","#ebebeb");
        //     $(".footerBtn").attr("canDo",0);
        //     $(".footerBtn").html("缺货");
        // }
        // $(".inventory").html(inventoryArr[index]);
        // $(".carAndBuyMarsk .pic").attr("data-skuId",skuIdArr[index]);
        // $(".carAndBuyMarsk .pic img").attr("src",picArr[index]);
        // $(".skuPrice").html(priceArr[index].toFixed(2));
        // $(".skuPrice").attr("data-diamond",diamondArr[index].toFixed(2));
        // $(".skuPrice").attr("data-cash",cashArr[index].toFixed(2));
    });
    $(".buy").on("click", function () {
        marskAnimate("立即购买", 1);
    });
    function marskAnimate(str, status) {
        var width = window.screen.availWidth;
        var height = window.screen.availHeight;
        var canDo = parseInt($(".footerBtn").attr("canDo"));
        var inventory = parseInt($(".inventory").html());
        if (canDo === 0) {
            $(".footerBtn").html("缺货");
        } else if (canDo === 1) {
            $(".footerBtn").html(str);
        }
        $(".footerBtn").attr("data-status", status);
        $(".carAndBuyMarsk").css({
            "width": width,
            "height": height,
            "background-color": "rgba(0,0,0,.6)",
            "display": "block"
        });
        $(".cbmBox").animate({
            "bottom": 0
        }, 600);
    }
    //关闭弹出层
    $(".carAndBuyMarsk").on("click", ".closeBtn", function (e) {
        e.stopPropagation();
        cbmBoxAnimate();
    });
    function cbmBoxAnimate() {
        $(".carAndBuyMarsk").css("background-color", "rgba(0,0,0,0)");
        $(".footerBtn").html("");
        $(".cbmBox").animate({
            "bottom": -830
        }, 500, function () {
            $(".carAndBuyMarsk").css("display", "none");
        });
    }
    $(".cbmBox").on("click", function (event) {
        event.stopPropagation();
    });
    //商品加减
    $(".carAndBuyMarsk").on("click", ".add", function () {
        var inventory = parseInt($(".inventory").html());
        var num = parseFloat($(".addOrCut .num").html());
        num++;
        if (num > inventory) {
            $(".footerBtn").css("background-color", "#ebebeb");
            $(".footerBtn").html("缺货");
            $(".footerBtn").attr("canDo", 0);
        }
        $(".addOrCut .num").html(num);
    });
    $(".carAndBuyMarsk").on("click", ".cut", function () {
        var inventory = parseInt($(".inventory").html());
        var num = parseFloat($(".addOrCut .num").html());
        if (num === 1) {
            return;
        } else {
            num--;
            if (num <= inventory) {
                $(".footerBtn").css("background-color", "#1f1f1f");
                if (parseInt($(".footerBtn").attr("data-status")) === 0) {
                    $(".footerBtn").html("加入购物车");
                } else if (parseInt($(".footerBtn").attr("data-status")) === 1) {
                    $(".footerBtn").html("立即购买");
                }
                $(".footerBtn").attr("canDo", 1);
            }
            $(".addOrCut .num").html(num);
        }
    });
    //将商品加入购物车或者购买商品
    function tips(tips) {
        $(".tips").css("display", "block").html(tips).animate({
            "opacity": 1
        }, 1000, function () {
            setTimeout(function () {
                $(".tips").animate({
                    "opacity": 0
                }, 1000, function () {
                    $(".tips").css("display", "none");
                })
            }, 1000);
        })
    }
    $(".carAndBuyMarsk").on("click", ".footerBtn", function () {
        var canDo = parseInt($(this).attr("canDo"));
        if (canDo === 0) return false;
        if (canDo === 1) {
            var status = parseInt($(this).attr("data-status"));
            if (status === 0) {
                var skuId = parseInt($(".carAndBuyMarsk .pic").attr("data-skuId"));
                var count = parseInt($(".carAndBuyMarsk .num").html());
                console.log(skuId, count, token);
                $.ajax({
                    type: "post",
                    url: domain.test + "/addcar",
                    data: {
                        skuId: skuId,
                        count: count
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("token", token);
                        xhr.setRequestHeader("version", "iOS2.91");
                    },
                    success: function (response) {
                        console.log(response);
                        if(response.data.rtnCode===200) {
                            cbmBoxAnimate();
                            tips("成功加入购物车");
                        }
                        if (response.data.rtnCode === 401) {
                            var outTimeCode = response.data.rtnCode;
                            location.href = "../../index.html?outTimeCode=" + outTimeCode;
                        }
                    }
                });
            } else if (status === 1) {
                var productObj = [];
                var productItem = {};
                var totalPrice = parseInt($(".carAndBuyMarsk .num").html()) * parseFloat($(".skuPrice").html());
                console.log(totalPrice);
                productItem.img = $(".carAndBuyMarsk .pic img").attr("src");
                productItem.productName = $(".product_Name .name").html();
                productItem.sku = $(".showSku").html();
                productItem.price = $(".skuPrice").html();
                productItem.diamond = parseFloat($(".skuPrice").attr("data-diamond")).toFixed(2);
                productItem.cash = $(".skuPrice").attr("data-cash");
                productItem.count = $(".carAndBuyMarsk .num").html();
                productObj.push(productItem);
                localStorage.sureOrderProductDetail = JSON.stringify(productObj);
                localStorage.totalPrice = totalPrice.toFixed(2);
                console.log(JSON.parse(localStorage.sureOrderProductDetail));
                location.href = "../me/sureOrder.html";
            }
        }
    });
});